﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using Citi.GenericApplications.SchedulerUi.EmailSenderWcf;
using Citi.RoutineBase;

namespace Citi.PTSConsolidation.SchedulerUI
{
    public class ReportAvailableEmail : IExecutableRoutine
    {
        private string PivotImagePath = ConfigurationManager.AppSettings["PivotImagePath"];
        private string EmailAvailableXMLPath = ConfigurationManager.AppSettings["EmailAvailableXMLPath"];

        private const string HtmlWithImage = @"
                <tr>
                    <td><span style=""font-size:12pt; color:blue; font-weight:bold;"">{0}</span></td>
                    <td align=""right""><span style=""font-size:11pt; color:blue;"">{2}</span></td> 
                </tr>
                <tr>
                    <td colspan = ""2"">
                        <img src=""cid:{3}"" alt=""{3}"" />
                    </td>
                </tr>
                <tr><td colspan = ""2""><a href=""{1}"" style=""font-size:9pt; color:blue;"">{1}</a><br /><br /></td></tr>";
        private const string HtmlWithoutImage = @"<tr><td><a href=""{1}"">{0}</a></td><td>{2}</td></tr>";

        public IEnumerable<RoutineParameter> Parameters
        {
            get { return null; }
        }

        public void Rollback(ref ICurrentAction currentAction, Dictionary<string, object> parameters)
        {

        }

        public void Start(DateTime scheduledDate, ref ICurrentAction currentAction, Dictionary<string, object> parameters)
        {
            var reports = Helpers.XmlHelper.DeserializeFromXml<List<Domain.ReportEmail>>(EmailAvailableXMLPath)
                .Where(x => (x.EndMonth == 0 && x.StartMonth == 0)
                || (x.StartMonth > 0 && DateTime.Today.Month >= x.StartMonth)
                || (x.EndMonth > 0 && DateTime.Today.Month <= x.EndMonth));
            var users = reports.Select(x => x.Users).Distinct();
            var attachments = new List<Attachment>();

            foreach (var user in users)
            {
                var htmlPivotImageEmail = string.Empty;
                var htmlNormalEmail = string.Empty;
                var htmlNotFound = string.Empty;
                var userReports = reports.Where(x => x.Users == user).OrderBy(x => x.FriendlyName);

                foreach (var userReport in userReports)
                {
                    var reportPath = FillVariables(userReport.ReportPath);

                    if (!File.Exists(reportPath))
                    {
                        htmlNotFound += string.Format(HtmlWithoutImage, FillVariables(userReport.FriendlyName), Path.GetDirectoryName(reportPath),
                            "Unavailable");
                        continue;
                    }

                    string pivotImagePath;
                    var htmlContent = HtmlWithoutImage;

                    if (!string.IsNullOrWhiteSpace(userReport.PivotTableName) && !string.IsNullOrWhiteSpace(userReport.SheetName))
                    {
                        pivotImagePath = Path.Combine(PivotImagePath, string.Format("{0}.bmp", Path.GetFileNameWithoutExtension(reportPath).Split('_')[0]));
                        Helpers.ExcelHelper.GetPivotTableImage(reportPath, userReport.PivotTableName, userReport.SheetName, pivotImagePath, null);
                        htmlContent = string.Format(HtmlWithImage, FillVariables(userReport.FriendlyName), Path.GetDirectoryName(reportPath),
                            File.GetCreationTime(reportPath).ToString("dd/MM/yyyy"), Path.GetFileName(pivotImagePath));

                        htmlPivotImageEmail += htmlContent;

                        attachments.Add(new Attachment { PathFile = pivotImagePath, FriendlyName = Path.GetFileName(pivotImagePath) });
                        continue;
                    }

                    htmlNormalEmail += string.Format(htmlContent, FillVariables(userReport.FriendlyName), Path.GetDirectoryName(reportPath),
                        File.GetCreationTime(reportPath).ToString("dd/MM/yyyy HH:mm"));
                }

                InsertEmailOnQueue(user, htmlPivotImageEmail, htmlNormalEmail + htmlNotFound, attachments);
            }
        }

        private void InsertEmailOnQueue(string to, string htmlPivotContent, string htmlNormal, List<Attachment> attachments)
        {
            using (var client = new EmailClient())
            {
                var email = new Email
                {
                    To = to.Split(';').Select(x => new EmailAddress { Description = x }).ToList(),
                    Parameters = new Dictionary<string, string>() { { "[ReportsAvailable]", htmlPivotContent }, { "[ReportsAvailableNormal]", htmlNormal } },
                    TemplateId = 2973,
                    Attachments = attachments
                };

                client.InsertEmailInQueue(email);
            }
        }

        private string FillVariables(string value)
        {
            value = value.Replace("[Year]", DateTime.Today.ToString("yyyy"));
            value = value.Replace("[NextYear]", DateTime.Today.AddYears(1).ToString("yyyy"));
            value = value.Replace("[PreviousYear]", DateTime.Today.AddYears(-1).ToString("yyyy"));
            value = value.Replace("[Month]", DateTime.Today.ToString("MM"));
            value = value.Replace("[Day]", DateTime.Today.ToString("dd"));

            return value;
        }

        public void Stop(ref ICurrentAction currentAction, Dictionary<string, object> parameters)
        {

        }
    }
}
